#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "single_list.h"

#if !defined(SINLGE_LIST_LW)

S_node *create_node(void)
{
    S_node *new_node = NULL;
    
    new_node = (S_node *)malloc(sizeof(S_node));
    if (NULL == new_node)
    {
	return NULL;
    }

    new_node->next = NULL;
    new_node->elem = -1;

    return new_node;
}

void destroy_node(S_node *node)
{
    if(NULL == node)
    {
	return;
    }

    free(node);
    return;
}

S_list create_list(void)
{
    S_list new_list = NULL;

    new_list = (S_list)malloc(sizeof(S_node));
    if (NULL == new_list)
    {
	return NULL;
    }

    new_list->next = NULL;
    new_list->elem = -1;

    return new_list;
}

void destroy_list(S_list list)
{
    if (NULL == list)
    {
	return;
    }

    S_node *del_node = NULL;
    for (list; list->next != NULL; del_node = list->next)
    {
	del_node = list->next;
	list->next = del_node->next;
	free(del_node);
	del_node = NULL;
    }

    free(list);
    list = NULL;
}

S_list insert_to_head(S_list head, S_node *node)
{
    if (NULL == head || NULL == node)
    {
	exit(0);
    }

    node->next = head->next;
    head->next = node;
    
    return head;
}

S_list insert_to_tail(S_list head, S_node *node)
{
    if (NULL == head || NULL == node)
    {
	printf("Invalid parameters\n");
	return NULL;
    }

    S_node *tmp = NULL;

    for(tmp = head; tmp->next != NULL; tmp = tmp->next);

    tmp->next = node;

    return head;
}

S_list remove_node(S_list head, S_node *node)
{
    if (NULL == head || NULL == node)
    {
	printf("Invalid parameters\n");
	return NULL;
    }

    S_node *tmp = NULL;
    S_node *prev = NULL;

    for (prev = head; prev->next != NULL; )
    {
	if (node->elem == prev->next->elem)
	{
	    tmp = prev->next;
	    prev->next = prev->next->next;
	    free(tmp);
	    tmp = NULL;
	    continue;
	}

	prev = prev->next;
    }

    return head;
}
#endif
